package com.domor.controller.system;

import com.domor.model.Result;
import com.domor.model.User;
import com.domor.service.system.SystemService;
import com.domor.utils.DigestUtil;
import com.domor.utils.MapUtils;
import com.domor.utils.ParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
public class SystemController {

    @Autowired
    private SystemService service;

    @RequestMapping("/login")
    public Result login(HttpServletRequest request) {
        Map<String, Object> params = ParamUtils.getParams(request);
        String username = MapUtils.getStringValue(params, "username");
        String password = MapUtils.getStringValue(params, "password");
        User user = service.getUserByName(username);
        if (user == null) {
            return Result.error("用户不存在！");
        } else if (!user.getPassword().equals(DigestUtil.md5(password))) {
            return Result.error("密码错误！");
        } else {
            request.getSession().setAttribute("user", user);
            return Result.success(user.getUsername());
        }
    }

    @RequestMapping("/getUserInfo")
    public Result getUserInfo(HttpSession session) {
        User user = (User) session.getAttribute("user");
        Map<String, Object> data = new HashMap<>();
        data.put("user", user);
        data.put("menus", service.getUserMenus(user.getRole()));
        data.put("buttons", service.getUserButtons(user.getRole()));
        return Result.success(data);
    }

    @RequestMapping("/logout")
    public Result logout(HttpSession session) {
        session.removeAttribute("user");
        return Result.success("");
    }

}
